//
// Created by 28365 on 2025/3/9.
//

#include "../include/obj/File.h"
#include "../include/exception/FileWriteExcpetion.h"
#include <iostream>

File::File(const string& path) : path(fs::path(path)) {}

bool File::isExists() {
    return filesystem::exists(path);
}

ofstream *File::openOutStream() {
    if (outStream != nullptr){
        delete outStream;
        outStream = new ofstream(path);
    } else{
        outStream = new ofstream(path);
    }
    if (!outStream->is_open()){
        throw FileWriteException("文件无法打开");
    }
    return outStream;
}

ofstream *File::openOutStream(_Ios_Openmode mode) {
    if (outStream != nullptr){
        delete outStream;
        outStream = new ofstream(path,mode);
    } else{
        outStream = new ofstream(path,mode);
    }
    if (!outStream->is_open()){
        throw FileWriteException("文件无法打开");
    }
    return outStream;
}

ifstream *File::openInStream() {
    if (inStream != nullptr){
        delete inStream;
        inStream = new ifstream(path);
    } else{
        inStream = new ifstream(path);
    }
    inStream = new ifstream(path);
    if (!inStream->is_open()){
        throw FileWriteException("文件无法打开");
    }
    return inStream;
}

bool File::deleteFile() {
    return filesystem::remove(path);
}

File::~File() {
    if (outStream != nullptr){
        if (outStream->is_open()){
            outStream->flush();
            outStream->close();
        }
        delete outStream;
    }
    if (inStream != nullptr){
        if (inStream->is_open()){
            inStream->close();
        }
        delete inStream;
    }
}

bool File::mkdirs() {
    return fs::create_directories(path);
}

bool File::mkParentDirs() {
    return fs::create_directories(path.parent_path());
}

bool File::existsParentDir() {
    return fs::exists(path.parent_path());
}

fs::path File::getAbsolutePath() {
    return fs::absolute(path);
}

ifstream *File::openInStream(_Ios_Openmode mode) {
    if (inStream != nullptr){
        delete inStream;
        inStream = new ifstream(path,mode);
    } else{
        inStream = new ifstream(path,mode);
    }
    if (!inStream->is_open()){
        throw FileWriteException("文件无法打开");
    }
    return inStream;
}
